<?php

/**
 * 橘袋 SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopjudai;
use App\Model\PssModel\ServiceConfig;
use App\Service\Code\Normal;
use App\Service\AppService\SystemCacheConfigService;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class ShopjudaiApiClient
{
    private $account  = 'Shopjudai';
    protected $config;
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        
        //商品下单组
        $orderGoodsList = [];
        $productAmt     = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item ) 
        {
           //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,2);
            
            //含税税率
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            
            //不含税价格
            $not_tax_price      = bcdiv((string)$singleGoodsPrice, (string)$tax_rate,3);
            $not_tax_price      = ceil(bcmul((string)$not_tax_price,(string)'100',1));
            $not_tax_price      = bcdiv((string)$not_tax_price,'100',2);
            
            //税金
            $singleGoodsTax     = bcsub((string)$singleGoodsPrice, (string)$not_tax_price,3);
            
            //单个商品总税金
            $totalGoodsTax  = bcmul((string)$singleGoodsTax,(string)$buyAcount,2); 
            
            //单个商品总不含税价格
            $totalGoods     = bcmul((string)$not_tax_price,(string)$buyAcount,2);
            
            //商品组
             $orderGoodsList[] = [
                'goods_id' => (int)$item['supplier_skucode'],
                'num'       => $buyAcount,
                'price'     => (float)$not_tax_price,
            ];
            $productAmt = bcadd((string)$productAmt,(string)$totalGoods,2);
            $TaxAmt = bcadd((string)$TaxAmt,(string)$totalGoodsTax,2);
        }

        //实际下单金额 
        $real_total_money = $orderInfo['real_total_money'];
        //订单总金额 = 不含税商品总金额 + 总税费 + 运费 - 优惠金额
        $ActualPaidAmt = bcadd((string)$productAmt,(string)$TaxAmt,2);
        $ActualPaidAmt = bcadd((string)$ActualPaidAmt,(string)$deliver_money,2);
        //优惠金额
        $discount_money = bcsub((string)$ActualPaidAmt,$real_total_money,2);
        
        //支付时间
        $pay_time       = $orderInfo['pay_time'] ? $orderInfo['pay_time'] : time();
        
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
      
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyName = $apply_extends['payCommanyName'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $payCommanyName = $order['payCommanyName'] ? $order['payCommanyName'] : $payCommanyName;
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        } 
        
        //电商平台信息
        $enterpriseNum = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        //创建订单数据
        $data = [
            'goods_data'              => $orderGoodsList,
            'real_pay'                => (float)$real_total_money,
            'discount_price'          => (float)$discount_money,
            'pay_time'                => (int)$pay_time,
            'receive_name'            => $orderInfo['receive_name'],
            'receive_phone'           => $orderInfo['recveive_phone'],
            'id_card'                 => $orderInfo['buyer_idcard'],
            'province'                => $orderInfo['province'],
            'city'                    => $orderInfo['city'],
            'area'                    => $orderInfo['district'],
            'address_detail'          => $orderInfo['receive_address'],
            'trxid'                   => $pay_sn,
            'ebpCode'                 => $enterpriseNum,
            'ebpName'                 => $enterpriseName,
            'payCode'                 => $PayCompanyCode,
            'payName'                 => $payCommanyName,
            'timestamp'               => (int)microtime(true)  
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        
        $res = $this->execute($requestParam);
        if( $res['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $res["data"]['data']
            ]);
        }
        return $res;
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        return Normal::returnCode(Normal::SUC,"处理成功");
    }
    
    
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( array $param = [] )
    {
        //第一步：将所有参数（注意是所有参数）加上key=>key值（系统提供），除去sign本身，以及值是空的参数，按参数名字母升序排序
        $param = array_filter($param);
        ksort($param);
        //第二步：把排序后的参数按参数1值1参数2值2…参数n值n（这里的参数和值必须是传输 参数的原始值，不能是经过处理的，如不能将”转成”后再拼接）的方式拼接成一个字符 串。
        $string="";
        foreach ($param as $k=>$v){
            if(is_array($v)){
                $v = json_encode($v, JSON_UNESCAPED_UNICODE);
            }
            $string.=$k."=".$v."&";
        }
        $string=substr($string,0, -1);
        //第三步：在上一步得到的字符串，然后计算md5值，得到32位字符串，然后转成大写,得到的字符串作为sign的值
        $string = strtoupper(md5($string));
        return $string;
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        
        $method = $param['method'];
        //加签
        $key=$this->config["key"];
        $SignData=array_merge($param['data'],array("key"=>$key));
        $param['data']['sign'] = $this->getSign($SignData);
        
        $url = $this->config['baseurl'];
        $token=$this->config["token"];
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => [
                    "token:{$token}" , 
                    "Content-Type: application/json"
                ],
        
            ],
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        
        $resHttp = json_decode($res,true);
        if( isset($resHttp['code']) && $resHttp['code'] == 0 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        
        $message = isset($resHttp['message']) ? $resHttp['message'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}